package com.perseygroup.apps;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.perseygroup.apps.tools.c2dm.C2DMService;
import com.perseygroup.apps.tools.ws.WsGeneral;

public class AuthentificationActivity extends GeneralActivity implements OnClickListener
{
	//private Spinner mEcole;
	private EditText mEcole;
	private EditText mIdentifiant, mPassword;
	private Button mValider, mAide, mAbout;
	private TextView mProgressStatus;
	private String button_yes = "Oui";
	private String button_no = "Non";
	private ProgressDialog mProgressDialog;
	private final Handler uiThreadCallback = new Handler();
	private int dataFlagLoading = -1;//1->chargement liste ecole//2->connexion
	
	private String[] mListeEcoles;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.authentification);
		
		//mEcole = (Spinner)findViewById(R.id.spinner_ecole);
		mEcole = (EditText)findViewById(R.id.spinner_ecole);
		mIdentifiant = (EditText)findViewById(R.id.editText_id);
		mPassword = (EditText)findViewById(R.id.editText_passwd);
		mValider = (Button)findViewById(R.id.auth_submit);
		mAide = (Button)findViewById(R.id.aide);
		mAbout = (Button)findViewById(R.id.about);
		mProgressStatus = (TextView)findViewById(R.id.progressSTatus);
		
		mValider.setOnClickListener(this);
		mEcole.setOnClickListener(this);
		mAbout.setOnClickListener(this);
		
		mProgressDialog = new ProgressDialog(this);
		
		dataFlagLoading = 1;
		//getListeEcoles();
		
		//Trying connexion with data connection save in prefs
		connexionWithPrefsData();
	}
	
	private void displayErrorMessage(int errorCode)
	{
		Builder alertDialog = new AlertDialog.Builder(this)
		.setTitle(R.string.errorMsgAlert_Title)
		.setCancelable(false)
		.setNeutralButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
			}
		});
		
		switch(errorCode)
		{
			case -1:
			{
				//Exception when contacting the serveur, ws or other.
				alertDialog.setMessage(R.string.errorMsgAlert_Exception);
				alertDialog.show();
			}
			break;
			case -2:
			{
				//One of the fields is empty
				alertDialog.setMessage(R.string.errorMsgAlert_EmptyField);
				alertDialog.show();
			}
			break;
			case 0:
			{
				//Bad login or password
				alertDialog.setMessage(R.string.errorMsgAlert_BadLoginPassSchool);
				alertDialog.show();
			}
			break;
			case -3:
			{
				//Exception when contacting serveur for getting list school
				alertDialog.setMessage(R.string.errorMsgAlert_Exception);
				alertDialog.show();
			}
			break;
		}
	}
	
	@Override
	public void onBackPressed()
	{
		new AlertDialog.Builder(this)
		.setTitle(R.string.titre_quitter)
		.setMessage(R.string.confirmation_quitter)
		.setCancelable(false)
		.setPositiveButton(R.string.text_oui, new DialogInterface.OnClickListener() 
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				finish();
			}
		})
		.setNegativeButton(R.string.text_non, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				
			}
		})
		.show();
	}
	
	@Override
	public void onClick(View view) 
	{
		if(view == mValider)
		{
			String ecoleChoisie = (String)mEcole.getText().toString();
			dataFlagLoading = 2;
			
			if(ecoleChoisie.length() == 1 || mPassword.getText().toString().trim().length() == 0 || mIdentifiant.getText().toString().trim().length() == 0)
			{
				//Erreur un des champs vide
				displayErrorMessage(-2);
			}
			else
			{	
				//this.connexionStudent(ecoleChoisie, mIdentifiant.getText().toString(), mPassword.getText().toString());
				new ProgressTask().execute(ecoleChoisie, mIdentifiant.getText().toString(), mPassword.getText().toString());
			}
			//When we dont want to check the validity of the input data 
			//startActivityForResult(new Intent(this, MenuActivity.class), CREATE_REQUEST_CODE);
		}
		else if (view == mEcole)
		{
			showSchoolListInAlertDialog();
		}
		else if (view == mAbout)
		{
			startActivity(new Intent(this, AproposActivity.class));
		}
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(requestCode == CREATE_REQUEST_CODE)
		{
			switch(resultCode)
			{
				case RESULT_QUITTER:
				{
					//We reinitialize
					FROM_MENU_QUITTER = false;
					finish();
				}
				break;
				case RESULT_DECONNECTER:
				{
					startActivity(new Intent(this, this.getClass()));
					finish();
				}
				break;
			}
		}
	}
	
	private void submitResultTreatmeant(int reslt) {

		if(reslt == 1)
		{
			setStudentDataInPrefs(mIdentifiant.getText().toString(), mEcole.getText().toString(), mPassword.getText().toString());//Save the right login and school prefs.
			startActivityForResult(new Intent(this, MenuActivity.class), CREATE_REQUEST_CODE);
		}
		else
		{
			if(reslt == 0)
			{
				displayErrorMessage(0);
			}
			else
			{
				if(reslt == -1)
				{
					displayErrorMessage(-1);
				}
			}
		}
    }
	
	private void showSchoolListInAlertDialog()
	{
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.text_choose_school));
		builder.setItems(mListeEcoles, new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int item) {
		        //Toast.makeText(getApplicationContext(), listeEcoles[item], Toast.LENGTH_SHORT).show();
		        mEcole.setText(mListeEcoles[item]);
		    }
		});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	class ProgressTask extends AsyncTask<String, Void, Void>{
		String[] listeEcoles;
		@Override
		protected void onPreExecute() {
			switch(dataFlagLoading)
			{
				case 1:
					{
						mProgressDialog.setMessage(getString(R.string.text_chargement_liste_ecoles));
						// On affiche notre message
						mProgressDialog.show();
					}
					break;
				case 2:
				{
					mProgressDialog.setMessage(getString(R.string.text_chargement_connexion_etudiant));
					// On affiche notre message
					mProgressDialog.show();
				}
				break;
			}
		}
		
		
		@Override
		protected Void doInBackground(String... params) {
			
			switch(dataFlagLoading)
			{
				case 1:
				{
					listeEcoles = WsGeneral.getListeEcoles();
				}
				break;
				case 2:
				{
					resultSubmit = WsGeneral.connexionStudent(params[0], params[1], params[2]);
				}
				break;
			}
			
			//j' arrete ici ma barre de progression
			mProgressDialog.dismiss();
			
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			
			switch(dataFlagLoading)
			{
				case 1:
				{    
					mListeEcoles = listeEcoles;
					
					if(mListeEcoles.length == 0)
					{
						displayErrorMessage(-3);
					}
				}
				break;
				case 2:
				{
					submitResultTreatmeant(resultSubmit);
				}
				break;
			}
		}
	}
	
	private void getListeEcoles()
	{
		new ProgressTask().execute();
	}
	
	//Method for connecting to the app when the connection data are set in prefs.
	private void connexionWithPrefsData()
	{
		if(FROM_MENU_QUITTER == false)
		{
			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
			
			//If is checked
			if(pref.getBoolean("pref_student_data_connexion", false))
			{
				String[] studentData = getStudentDataFromPrefs();
				
				mEcole.setText(studentData[1]);
				mIdentifiant.setText(studentData[0]);
				mPassword.setText(studentData[2]);
				
				dataFlagLoading = 2;
				
				//School, Login, Password
				new ProgressTask().execute(mEcole.getText().toString(), mIdentifiant.getText().toString(), mPassword.getText().toString());
			}
			else
			{
				getListeEcoles();
			}
		}
	}
}